package com.ocom.xcxapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.entity.master.EntityWechatPerInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.HttpRequest;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.oauth.AppInfo;
import com.ocom.redis.util.RedisUtil;
import com.ocom.xcxapi.client.CompanyClientService;
import com.ocom.xcxapi.client.HumanClientService;
import com.ocom.xcxapi.service.CompanyService;
import com.ocom.xcxapi.util.CardList;
import com.ocom.xcxapi.util.HttpResult;
import com.ocom.xcxapi.util.HttpResultCard;
import com.ocom.xcxapi.util.HttpResultData;
import com.ocom.xcxapi.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


@Slf4j
@Service
public class CompanyServiceImpl implements CompanyService {

    @Value("${xcx.appid}")
    private String appId;
    @Value("${xcx.secret}")
    private String secret;


    //绑定到单位的默认值
    public  static Map<String , AppInfo> app = new HashMap(){
        {
            put("39", new AppInfo("wxcb170317c5a70550","3427c300b77c8a1fc216d4af4f39a992"));
            put("639", new AppInfo("wx31ce24812ee29ba5","fcc7512e482474b07463041ac1ffbb16"));

        }
    };

    @Resource
    RedisUtil redisUtil;

    @Autowired
    private CompanyClientService companyClientService;

    @Autowired
    private HumanClientService humanClientService;

    //获取卡列表（user/getCardListInfo）
    @Override
    public Result UserGetCardListInfo(String openid) {
        String url = "http://120.78.153.235:20000/o2api/api/HomePage/onShow";

        String param = "appid=" + appId + "&openid=" + openid;
        String result = HttpRequest.sendPost(url, param);
        Gson gson = new Gson();
        HttpResult httpResult = gson.fromJson(result, HttpResult.class);

        log.info("httpResult{{}}", httpResult);


        Map<Object, Object> datamap = new HashMap<>();
        List<Object> list = new ArrayList<>();

        if(httpResult!=null){
            HttpResultData data = httpResult.getData();
            List<HttpResultCard> cardList = data.getCardList();
            for (HttpResultCard httpResultCard : cardList) {
                Map<String, Object> map = new HashMap<>();
                map.put("comId", httpResultCard.getCompanyID());
                map.put("pId", httpResultCard.getP_ID());
                map.put("comName", httpResultCard.getCompanyName());
                map.put("color", httpResultCard.getBackColor());
                map.put("version", 2.0);
                list.add(map);
            }
        }

        Result result1 = companyClientService.GetCompanyInfoByUser(openid);
        log.info("result1{{}}", result1);
        if (result1.getCode() != 200) {
            return ResultUtil.error(result1.getCode());
        }
        List<CardList> cardLists = JSON.parseArray(JSON.toJSONString(result1.getData()), CardList.class);
        for (CardList cardList1 : cardLists) {
            CardList cardList2 = new CardList();
            cardList2.setComId(cardList1.getComId());
            cardList2.setPId(cardList1.getPId());
            cardList2.setComName(cardList1.getComName());
            cardList2.setVersion(cardList1.getVersion());
            cardList2.setColor(cardList1.getColor());
            list.add(cardList2);
        }
        datamap.put("carddata", list);
        datamap.put("total", list.size());
        log.info("datamap{{}}", datamap);
        return ResultUtil.success(datamap);
    }


    /**
     * 2.5.手机号绑定(user/bindPhone)
     */
    @Override
    public Result UserBindPhone(Long comId, String code, String openid) {

        String newAppid = appId;
        if(app.containsKey(String.valueOf(comId))){
            newAppid = app.get(String.valueOf(comId)).getAppId();
        }

        log.info("绑卡：【{}】【{}】【{}】【{}】",comId,code,openid,newAppid);
        String accessToken = (String) redisUtil.get(newAppid);

        if (accessToken == null) {
            accessToken = getAccessToken(comId);
            redisUtil.set(newAppid, accessToken, 7199L);
        }
        Gson gson = new Gson();
        String PhoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        //发送json请求，对象必须封装成json格式
        JSONObject params = new JSONObject();
        params.put("code", code);
        //注意！一定要将对象转成字符串
        String str = params.toJSONString();
        String PhoneNumber = HttpRequest.sendPost(PhoneNumberUrl, str);
        log.info("获取手机号1 【{}】【{}】【{}】",PhoneNumber,PhoneNumberUrl,code);
        GetPhoneNumberVo getPhoneNumberVo = gson.fromJson(PhoneNumber, GetPhoneNumberVo.class);
        PhoneInfoVo phone_info = getPhoneNumberVo.getPhone_info();
        if (phone_info == null) {
            log.info("获取手机号 【{}】",getPhoneNumberVo);
            return ResultUtil.error(ResultEnum.Err_1001, "获取手机号");
        }
        //  手机号 /getPhoneNumber
        String phoneNumber = phone_info.getPhoneNumber();
        log.info("phoneNumber{{}}", phoneNumber);
        System.out.println(phoneNumber);
        //手机号获取凭证
        Map<String, Object> map = new HashMap<>();
        MapKey key = new MapKey();
        map.put(key.getKey_comId(), comId);
        map.put(key.getKey_pPhone(), phoneNumber);
        Result result1 = humanClientService.GetPersonInfoByPhoneOrCard(map);
        if (result1.getCode() != 200) {
            return ResultUtil.error(result1.getCode());
        }
//        String string = JSON.toJSONString(result1.getData());
//        System.out.println(string);

//        EntityPersonnelInfo personnelInfo = gson.fromJson(string, EntityPersonnelInfo.class);
        EntityPersonnelInfo personnelInfo = JSON.parseObject(JSON.toJSONString(result1.getData()),EntityPersonnelInfo.class);
        if (personnelInfo==null){
            return ResultUtil.error(ResultEnum.Err_303);
        }

        EntityWechatPerInfo entityWechatPerInfo = new EntityWechatPerInfo();
        entityWechatPerInfo.setComId(comId);
        entityWechatPerInfo.setPId(personnelInfo.getPId());
        entityWechatPerInfo.setOpenid(openid);
        entityWechatPerInfo.setCreateTime(new Date());
        entityWechatPerInfo.setAppid(newAppid);
        entityWechatPerInfo.setCardId(null);
        Result result = humanClientService.addWxper(entityWechatPerInfo);
        if (result.getCode() != 200) {
            return ResultUtil.error(result.getCode());
        }

        Result result2 = companyClientService.GetCompanyInfoByUser(openid);
        if (result2.getCode() != 200) {
            return ResultUtil.error(result2.getCode());
        }
        List<CardList> list = new ArrayList<>();
        List<CardList> cardLists = JSON.parseArray(JSON.toJSONString(result2.getData()), CardList.class);
        for (CardList cardList : cardLists) {
            CardList cardList2 = new CardList();
            cardList2.setComId(cardList.getComId());
            cardList2.setPId(cardList.getPId());
            cardList2.setComName(cardList.getComName());
            cardList2.setVersion(cardList.getVersion());
            cardList2.setColor(cardList.getColor());
            list.add(cardList2);
        }

        return ResultUtil.success(list);
    }

    /**
     * 2.6.注册码绑定(user/registerCode)
     */
    @Override
    public Result UserRegisterCode(RegisterCodeVo registerCodeVo) {
        Result result = companyClientService.GetRegCodeInfo(registerCodeVo.getRegCode(), registerCodeVo.getComId());
        Gson gson = new Gson();
        RegCodeInfoVo regCodeInfoVo = gson.fromJson(JSON.toJSONString(result.getData()), RegCodeInfoVo.class);
        List<RegCodeInfo> list = regCodeInfoVo.getList();

        if (regCodeInfoVo.getTotal() == 0) {
            return ResultUtil.error(ResultEnum.Err_1001);
        }
        for (RegCodeInfo regCodeInfo : list) {
            //2. 绑定用户
            EntityWechatPerInfo entityWechatPerInfo = new EntityWechatPerInfo();
            entityWechatPerInfo.setComId(registerCodeVo.getComId());
            entityWechatPerInfo.setPId(regCodeInfo.getPId());
            entityWechatPerInfo.setOpenid(registerCodeVo.getOpenid());
            entityWechatPerInfo.setAppid(appId);
            if(app.containsKey(String.valueOf(registerCodeVo.getComId()))){
                entityWechatPerInfo.setAppid(app.get(String.valueOf(registerCodeVo.getComId())).getAppId());
            }
            entityWechatPerInfo.setCardId(registerCodeVo.getCardId());
            try {
                Result result1 = humanClientService.addWxper(entityWechatPerInfo);
                if (result1.getCode() != 200) {
                    return ResultUtil.error(result1.getCode());
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }


        }

        Result result1 = companyClientService.GetCompanyInfoByUser(registerCodeVo.getOpenid());
        if (result1.getCode() != 200) {
            return ResultUtil.error(result1.getCode());
        }
        List<CardList> cardLists = JSON.parseArray(JSON.toJSONString(result1.getData()), CardList.class);

        return ResultUtil.success(cardLists);
    }


    /**
     * 卡应用首页信息 menjin/getCardConfig
     */
    @Override
    public Result MenjinGetCardConfig(Long comId, Long pId) {
        Result result = humanClientService.GetPersonInfo(comId, pId);
        if (result.getCode() != 200) {
            return ResultUtil.error(result.getCode());
        }
        EntityPersonnelInfo entityPersonnelInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityPersonnelInfo.class);
        if (entityPersonnelInfo == null) {
            return ResultUtil.error(ResultEnum.Err_1001);
        }
        Boolean openBtn = true;
        Boolean recordBtn = true;
        Map<String, Object> map = new HashMap<>();
        map.put("pName", entityPersonnelInfo.getPName());
        map.put("openBtn", openBtn);
        map.put("recordBtn", recordBtn);
        return ResultUtil.success(map);
    }


    private String getAccessToken(Long comId) {
        //接口调用凭证 /getAccessToken
        String getAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        if(app.containsKey(String.valueOf(comId))){
            AppInfo appInfo = app.get(String.valueOf(comId));
            getAccessToken = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appInfo.getAppId() + "&secret=" + appInfo.getAppSecret();
        }
        String result = HttpRequest.sendGet(getAccessToken);
        Gson gson = new Gson();
        GetAccessTokenVo getAccessTokenVo = gson.fromJson(result, GetAccessTokenVo.class);
        return getAccessTokenVo.getAccess_token();
    }

}
